import React from 'react';
import { Row, Col, Form, Icon, Input, Button, message } from 'antd';
import { FormProps } from 'antd/lib/form';
import axios from 'axios';

const NormalChangePasswordForm = (props: FormProps) => {
  const handleSubmit = (e: any) => {
    e.preventDefault();
    if (props.form !== undefined) {
      props.form.validateFields((err: any, values: any) => {
        if (!err) {
          if (values.newPassword !== values.newPasswordRepeat) {
            message.error('两次输入的新密码不一致，请检查！');
            return;
          }
          axios
            .put('/password', values)
            .then(() => {
              message.success('修改密码成功！');
            })
            .catch((error) => {
              if (error.response?.status === 400) {
                message.error('旧密码错误！');
              }
            });
        }
      });
    }
  };

  if (props.form !== undefined) {
    const { getFieldDecorator } = props.form;
    return (
      <Form onSubmit={handleSubmit}>
        <Form.Item>
          {getFieldDecorator('oldPassword', {
            rules: [{ required: true, message: '请输入旧密码' }]
          })(
            <Input.Password
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="旧密码"
            />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('newPassword', {
            rules: [{ required: true, message: '请输入新密码' }]
          })(
            <Input.Password
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="新密码"
            />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('newPasswordRepeat', {
            rules: [{ required: true, message: '请再次输入新密码' }]
          })(
            <Input.Password
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="新密码"
            />
          )}
        </Form.Item>
        <Form.Item>
          <Row>
            <Col span={12} offset={6}>
              <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                修改密码
              </Button>
            </Col>
          </Row>
        </Form.Item>
      </Form>
    );
  }
  return <div>error</div>;
};

const ChangePasswordForm = Form.create({ name: 'normal_change_password' })(
  NormalChangePasswordForm
);

const ChangePassword = () => {
  return (
    <Row>
      <Col span={8} offset={8}>
        <ChangePasswordForm />
      </Col>
    </Row>
  );
};

export default ChangePassword;
